import os
import sys
try:
    import tc
except:
    import pytc as tc
import struct
import pickle
import datetime

DBNAME = 'data.bdb'
db = tc.BDB()
db.setcache(1, 1)
db.open(DBNAME, tc.BDBOWRITER | tc.BDBOCREAT)

KEY_NODE_PREFIX = 'key_node_'
KEY_THREAD_PREFIX = 'key_thread_'

KEY_THREAD_ID_LIST = 'key_thread_id_list'

def new_node(title, content, **kargs):
    node = {'title':title, 'content':content}
    try:
        id = struct.unpack('i', db.get('id'))[0]
    except:
        db.put('id',struct.pack('i',0))
        id = struct.unpack('i', db.get('id'))[0]
    db.addint('id', 1)
    
    node['id'] = str(id)
    node['key'] =  KEY_NODE_PREFIX + node['id']
    node['nodes'] = []
    node['time'] = str(datetime.datetime.now()).split('.')[0]
    node['comment_cnt'] = 0
    node['isdel'] = 0 
    
    for addition in kargs.keys():
        node[addition] = kargs[addition]
    
    value = pickle.dumps(node)
    db.put(node['key'], value)
    return node


def new_thread(title, content,**kargs):
    node = new_node(title,content, **kargs)
    thread_key = KEY_THREAD_PREFIX + node['id']
    db.put(thread_key,node['key'])
    
    # append to thread list
    lst_thread = get_thread_id_list()
    lst_thread.append(int(node['id']))
    db.put(KEY_THREAD_ID_LIST, pickle.dumps(lst_thread))
    
    return node

def get_thread_id_list():
    try:
        lst_thread = db.get(KEY_THREAD_ID_LIST)
        lst_thread = pickle.loads(lst_thread)
    except:
        db.put(KEY_THREAD_ID_LIST, pickle.dumps([]))
        lst_thread = []
    return lst_thread
        
def new_comment(id, title, content,**kargs):
    parent_key = KEY_NODE_PREFIX + id
    comment_node = new_node(title, content, **kargs)
    try:
        parent_node = db.get(parent_key)
    except:
        return None
    parent_node = pickle.loads(parent_node)
    #print parent_node
    parent_node['nodes'].append(comment_node)
    parent_node['comment_cnt'] = len(parent_node['nodes'])
    db.put(parent_key, pickle.dumps(parent_node))
    return comment_node

def get_threads(**kargv):
    ret = []
    
    thread_id_list = sorted(get_thread_id_list(), key = lambda a: -a)
    #reversed(thread_id_list)
    keys = []
    for thread_id in thread_id_list:
        keys.append(KEY_NODE_PREFIX + str(thread_id))
    
    for key in keys:
        node = pickle.loads(db.get(key))
        if node['isdel'] == 0:
            ret.append(node)
    return ret
    
def get_node(id):
    key = KEY_NODE_PREFIX + id
    try:
        node = db.get(key)
    except:
        return None
    return pickle.loads(node)

def del_node(id):
    node = get_node(id)
    if node is not None:
        node['isdel'] = 1
        db.put(node['key'], pickle.dumps(node))
        return True
    return False   

# just for del node
if __name__ == '__main__':
   import sys,getopt
   try:
       opts, args = getopt.getopt(sys.argv[1:], "d:", ["del"])
   except getopt.GetoptError:
       sys.exit(2)
   for opt, arg in opts:
       if opt in ("-d", "--del"):
           id = arg
           if del_node(id) == True:
               print 'del node Success!'
           else:
               print 'del failed!'

